﻿/*
*	AUTHOR：K老叶
*	NAME：加密器
*	LICENSE：Apache License 2.0
*/


#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
#include"pch.h"
#pragma warning (disable:4996)
typedef unsigned char uchar;
typedef unsigned short ushort;
typedef unsigned int uint;
typedef unsigned long ulong;

uchar * encryption(uchar *psk, uchar *c)
{
	uchar *string;
	ushort ps, psk_len;
	uint lenth=strlen(c);
	ulong i;

	for (psk_len = 0; psk[psk_len] != 0; psk_len++);

	string = (uchar*)calloc(lenth * 2 , sizeof(uchar));//分配密文字符串大小
	//for (i = 0; i <= psk_len; i++)printf("%d\n", psk[i]);
	for (i = 0, ps = 0; i < (lenth * 2)+1; i++)
	{
		if (ps >= psk_len ) ps = 0;//8位密码循环
		//printf("i:%d|ps:%d|psk:%c\n", i, ps, psk[ps]); 
		string[i] = (c[i / 2] + psk[ps]) % 74 +48 ;//移位操作
		string[++i] = (c[(i - 1) / 2] + psk[ps++]) / 74;//补码
		//printf("i:%d|string:%c\n",i,string[i-1]);
	}
	//printf("--string:%d--lenth*2:%d--i:%d\n",string[i], lenth * 2 + 1,i);
	string[i] = 0;
	printf("密码长度：%d,密文长度:%d,明文长度%d\n", psk_len, strlen(string), lenth);
	return string;
}

uchar * decrypt(uchar *psk, uchar *ciphertext)
{
	uchar *c,*text;
	ushort ps, psk_len, *dot;
	uint lenth=strlen(ciphertext), i;
	
	for (psk_len = 0; psk[psk_len] != 0; psk_len++);

	c = (uchar*)calloc(lenth / 2+1, sizeof(uchar));//分配字符串空间
	text = (uchar*)calloc(lenth / 2 + 1, sizeof(uchar));//分配字符串空间
	dot = (ushort*)calloc(lenth / 2, sizeof(ushort));//分配补码数组空间
	//从密文中取出数据
	for (i = 0; i < lenth; i++)
	{

		c[i / 2] = ciphertext[i];
		dot[i / 2] = ciphertext[++i];
	}
	//for (i = 0; i <= lenth;i++)printf("%x\n", psk[i]);
	//解密操作
	for (i = 0, ps = 0; i < lenth / 2; i++)
	{
		if (ps >= psk_len ) ps = 0;//8位密码循环
		//printf("i:%d|ps:%d|psk:%c", i, ps,psk[ps]);
		text[i] = (dot[i] * 74 + (c[i] -48) ) - psk[ps++];//解码公式
		//printf("|text:%c\n",text[i]);
	}
	text[i] = 0;
	printf("密码长度：%d,明文长度:%d,密文长度%d\n",psk_len,strlen(c),lenth);
	return text;
}